<script setup>
import { ref, reactive, watch } from "vue";

// 第1个watch的例子
const count = ref(0);
function increment() {
  count.value++;
}
watch(count, (newCount, oldCount) => {
  console.log(`count changed from ${oldCount} to ${newCount}`);
});

// 第2个watch的例子
const firstName = ref("york");
const lastName = ref("chin");
watch(
  [firstName, lastName],
  ([newFirstName, newLastName], [oldFirstName, oldLastName]) => {
    console.log(
      `The first name is changed from ${oldFirstName} to ${newFirstName}`
    );
    console.log(
      `The last name is changed from ${oldLastName} to ${newLastName}`
    );
  }
);

// 第3个watch的例子
const user = reactive({ name: "John", age: 30 });
watch(
  user,
  (newUser) => {
    console.log(`User changed:`, newUser);
  },
  { deep: true, immediate: true }
);

// 第4个例子: 表单提交
const userName = ref("");
const errorMessage = ref("");
watch(userName, (newUserName) => {
  if (newUserName.length > 5) {
    errorMessage.value = "Username must be at least 5 characters long";
  } else {
    errorMessage.value = "";
  }
});
</script>


<template>
  <p>{{ count }}</p>
  <button @click="increment">Increment</button>
  <input type="text" v-model="firstName" />
  <input type="text" v-model="lastName" />
  <br />
  <input type="text" v-model.number="user.name" placeholder="John" />
  <input type="number" v-model.number="user.age" placeholder="年龄" />
  <div>
    <input v-model="userName" placeholder="Enter username" />
    <p v-if="errorMessage" style="color:red;">{{ errorMessage }}</p>
  </div>
</template>